/**
 * @author zhangqiang
 * @date   17/7/18
 */
import React, { Component } from 'react'
import {connect} from 'react-redux'
import {Toast} from 'antd-mobile'
import {
	InputItem,
} from '../../components/home'

//通用组件
import {Title} from '../../components/common'

import {
	verifyCode
} from  '../../actions/addInfoActions'
import {
    confirmOrder
} from  '../../actions/homeActions'
verifyCode
import '../../../styles/addInfo.scss';
import common from '../../utils/common'
import style from './index.scss'

var SEND;
class AddInfo extends Component {
	constructor(props) {
	super(props);
	this.state = {
		verifyCodeText: "获取验证码",	
		name: '',	
		cardId: '',
		phone: '',
		verifyCode: ''
	};
	}

	componentWillMount() {
		this.setState(
			Object.assign({}, JSON.parse(sessionStorage.getItem('addInfoCache')))
		)	
	}
	
	componentDidMount() {  
		/*
		* 上传页面返回，继续倒计时
		*/      
		if(sessionStorage.getItem('addInfoIsCountDown')){ 
			var second = sessionStorage.getItem('second'), //用来记录秒
				btnText;
			var that = this;
				SEND = setInterval(function () {
				second--;
				sessionStorage.setItem('second',second)//缓存秒数，用于上传图片回，到计时
				btnText = second + '秒后获取'; //显示时间
				that.setState({
					verifyCodeText: btnText
				});
				if (second == 0) {
				btnText = "重新发送";
				clearInterval(SEND);
				that.setState({
					verifyCodeText: btnText
				});
				} //到过60秒时停止
			}, 1000); //每1000毫秒即1秒执行一次此函数
		}
	}		
	componentWillUnmount(){
		//离开页面存储全局状态
		sessionStorage.setItem('addInfoCache', JSON.stringify(this.state))
		this.verifyCodeTap()

		clearInterval(SEND);

		sessionStorage.removeItem('addInfoIsCountDown')
    }

	toUrl(url) {
		this.context.router.push(url);
	}

	//倒计时
	countDown(result){
		let btnText = this.state.verifyCodeText;
		if (result.body != null) {
			Toast.info('验证码发送成功！',2)
			if (btnText === "获取验证码" || btnText === "重新发送") {
			btnText = '59秒后获取';    //第一次59秒
			var second = 59; //用来记录秒
			var that = this;
				let repeat= setInterval(function () {
				second--;
				sessionStorage.setItem('second',second)//缓存秒数，用于上传图片回，到计时
				btnText = second + '秒后获取'; //显示时间
				that.setState({
					verifyCodeText: btnText
				});
				if (second == 0) {
				btnText = "重新发送";
				clearInterval(repeat);
				that.setState({
					verifyCodeText: btnText
				});
				} //到过60秒时停止
			}, 1000); //每1000毫秒即1秒执行一次此函数
			}
		} else {
			Toast.info(result.msg,2)
		}
	}

	// 获取验证码
	verifyCodeTap() {
		var telephone = this.state.phone;
		var btnText = this.state.verifyCodeText;
		if (btnText != "获取验证码" && btnText != "重新发送") {
			return false;
		}
		if (telephone == '') {
			Toast.fail('请输入手机号码！',1)
			return false
		} else if (!/^0?1[3|4|5|7丨8][0-9]\d{8}$/.test(telephone)) {
			Toast.fail('请输入正确的手机号码！',1)
			return false;
		}
		let postData = {
			phoneNumber: telephone
		}

		this.props.dispatch(verifyCode(postData,(result)=>{
			this.countDown(result)
		}))
	}
	confirmOrder(){
		let idCardRule2 = /^[0-9]{17}([0-9]|X|x)$/,
			phoneRule = /^0?1[3|4|5|7丨8][0-9]\d{8}$/;
			
		//粤S H5X90    119704    let { carNumPrefix,carNumber,carCode }
		let {carNumPrefix,carNumber,carCode} = JSON.parse(sessionStorage.getItem('cacheAllState'));
		
		let	address = JSON.parse(sessionStorage.getItem('choiceAddress'));
		let { name,cardId,phone,verifyCode } = this.state;

		console.log(cardId)
		console.log('_________+++++',JSON.parse(sessionStorage.getItem('cacheAllState')))
		if(name == ''){
			Toast.info('请输入车主姓名！', 1)	
			return;		
		}else if(!/^[\u4e00-\u9fa5]{2,12}$/.test(name)){
			Toast.info('请输入正确的车主姓名!',1)
			return;
		}else if(cardId == ''){
			Toast.info('请输入身份证号!', 1)	
			return;		
		}else if(!idCardRule2.test(cardId)){
			Toast.info('请输入正确的身份证号!',1)
			return;
		}else if(phone == ''){
			Toast.info('请输入手机号码！',1)
			return;
		}else if(!phoneRule.test(phone)){
			Toast.info('请输入正确的手机号码!',1)
			return;
		}else if(verifyCode == ''){
			Toast.info('请输入验证码！',1)
			return;
		}else if(this.props.idCardImg.file.indexOf('http')==-1){
			Toast.info('请上传手持身份证照片!',1)
			return;
		}else if(this.props.insuranceImg.file.indexOf('http')==-1){
			Toast.info('请上传交强险保单副本!',1)
			return;
		}

		let postData = {
			cardPicture: this.props.idCardImg.file,//'http://yzres.oss-cn-shenzhen.aliyuncs.com/apptest/upload/2017/201711/20171128/wxapp/yaer/oFOEg0fX6iuC4Ix7LbLGkF7WWox0_66062.png',
			policyPicture: this.props.insuranceImg.file,//'http://yzres.oss-cn-shenzhen.aliyuncs.com/apptest/upload/2017/201711/20171128/wxapp/yaer/oFOEg0fX6iuC4Ix7LbLGkF7WWox0_66068.png',		
			
			cardName: name,
			cardNum: cardId,
			telephone: phone,

            carNumberSuffix: carNumPrefix,
            carNumPrefix: carNumPrefix,
            carNumber: carNumPrefix + carNumber,
			carCode: carCode,
			verifyCode: verifyCode,

            'address.contactName': address.contactName,
            'address.cellNum': address.cellNum,
            'address.provinceId': address.provinceId,
            'address.cityId': address.cityId,
            'address.countyId': address.countyId,
            'address.provinceName': address.provinceName,
            'address.cityName': address.cityName,
            'address.countyName': address.contactName,
            'address.street': address.street,
            'address.fullAddr': address.fullAddr,
		};
		
		let caCheConfirmOrder = JSON.parse(sessionStorage.getItem('payData'));
			caCheConfirmOrder['cardName'] = name
			caCheConfirmOrder['cardNum'] = cardId
			caCheConfirmOrder['telephone'] = phone
			caCheConfirmOrder['cardPicture'] = postData.cardPicture
			caCheConfirmOrder['policyPicture'] = postData.policyPicture
			
		console.log(caCheConfirmOrder)	
	
        this.props.dispatch(confirmOrder(postData,(result)=>{
            this.toUrl('payment')
			sessionStorage.setItem('payData',JSON.stringify(caCheConfirmOrder));  //缓存支付页面用
		}))
	}
	render() {
		console.log(this.props.idCardImg)
		console.log(this.props.insuranceImg)
		
		return (
			<div className={style.addInfo}>
				<Title text='补充资料' isLine={true} />
				<InputItem type="text" index='2' itemText="车主姓名" maxLength="12" placeHolder="请输入车主姓名" id="name"
					value={this.state.name} showUnderLine={true} showTagText={true} creditCodeImg={this.state.nameImg} creditWidth={this.state.nameWidth}
					onClick={() => {
						this.setState({
							name: '',
							nameImg: 'hideDelete',
							nameNoBlur: false
						})
						document.querySelector('#name').focus()
					} }
					onBlur={(event) => {
						let res = event.target.value;
						this.setState({ nameNoBlur: true });
						setTimeout(() => {
							if (!this.state.nameNoBlur) return;  //点击删除按钮不执行验证
							let value = res,
								nameRule1 = /^[\u4e00-\u9fa5]{2,12}$/;

							if (value == '') {
								this.setState({
									nameImg: '',
								});
							} else if (nameRule1.test(value)) {
								this.setState({
									nameImg: 'correct',
									nameWidth: '.4rem'
								});
							} else {
								this.setState({
									nameWidth: '.4rem',
									nameImg: 'error'
								})
							}
						}, 0)
					} }
					onFocus={(e) => {
						let value = e.target.value;
						if (value.length != 0 && value == this.state.name) {
							this.setState({
								nameImg: 'showDelete',
							});
						}
					} }

					onChange={(e) => {
						let value = e.target.value;
						if (value.length > 0 && value != ' ') {
							this.setState({
								nameImg: 'showDelete',
								name: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						} else {
							this.setState({
								nameImg: 'hideDelete',
								name: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}
				} } />
				<InputItem type="text" index='2' itemText="身份证号" maxLength="18" placeHolder="请输入身份证号" id='cardId'
					value={this.state.cardId} showUnderLine={true} showTagText={true} creditCodeImg={this.state.cardIdImg} creditWidth={this.state.cardIdWidth}
					onClick={() => {
						this.setState({
							cardId: '',
							cardIdImg: 'hideDelete',
							cardIdNoBlur: false
						})
						document.querySelector('#cardId').focus()
					} }
					onBlur={(event) => {
						let res = event.target.value;
						this.setState({ cardIdNoBlur: true });
						setTimeout(() => {
							if (!this.state.cardIdNoBlur) return;  //点击删除按钮不执行验证
							let value = res,
								idCardRule1 = /^[0-9]{14}([0-9]|X|x)$/,
								idCardRule2 = /^[0-9]{17}([0-9]|X|x)$/;

							if (value == '') {
								this.setState({
									cardIdImg: '',
								});
							} else if (idCardRule1.test(value)) {
								this.setState({
									cardIdImg: 'correct',
									cardIdWidth: '.4rem'
								});
							} else if (idCardRule2.test(value)) {
								this.setState({
									cardIdImg: 'correct',
									cardIdWidth: '.4rem'
								});
							} else {
								this.setState({
									cardIdWidth: '.4rem',
									cardIdImg: 'error'
								})
							}
						}, 0)
					} }

					onFocus={(e) => {
						let value = e.target.value;
						if (value.length != 0 && value == this.state.cardId) {
							this.setState({
								cardIdImg: 'showDelete',
							});
						}

					} }

					onChange={(e) => {
						let value = e.target.value;
						if (value.length > 0 && value != ' ') {
							this.setState({
								cardIdImg: 'showDelete',
								cardId: e.target.value.replace(/(^\s*)|(\s*$)/g, "").replace("x", 'X')
							});
						} else {
							this.setState({
								cardIdImg: 'hideDelete',
								cardId: e.target.value.replace(/(^\s*)|(\s*$)/g, "").replace("x", 'X')
							});
						}
				} } />
				<InputItem type="text" index='2' itemText="手机号码" maxLength="11" placeHolder="请输入手机号码" id="phone"
					value={this.state.phone} showUnderLine={true} showTagText={true} creditCodeImg={this.state.phoneImg} creditWidth = {this.state.phoneWidth}
					onClick={()=>{
						this.setState({
							phone: '',
							phoneImg: 'hideDelete',
							phoneNoBlur: false
						})
						document.querySelector('#phone').focus();
					}}
					onBlur={(event)=>{
						let res = event.target.value;
						this.setState({phoneNoBlur: true});
						setTimeout(()=>{
							if(!this.state.phoneNoBlur) return;  //点击删除按钮不执行验证
							let value = res,
								phoneRule = /^0?1[3|4|5|7丨8][0-9]\d{8}$/;

							if(value == ''){
								this.setState({
									phoneImg: '',
								});
							}else if(phoneRule.test(value)){
								this.setState({
									phoneImg: 'correct',
									phoneWidth: '.4rem'
								});
							}else {
								this.setState({
									phoneWidth: '.4rem',
									phoneImg: 'error'
								})
							}
						},0)
					}}

					onFocus={(e)=>{
						let value = e.target.value;
						if(value.length!=0&&value==this.state.phone){
							this.setState({
								phoneImg: 'showDelete',
							});
						}
					}}

					onChange={(e) => {
						let value = e.target.value;
						if(value.length>0&&value!=' '){
							this.setState({
								phoneImg: 'showDelete',
								phone: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}else {
							this.setState({
								phoneImg: 'hideDelete',
								phone: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}
				}}/>
				<div className={style.code}>
					<InputItem type="text" index='2' itemText="验证码" maxLength="11" placeHolder="请输入验证码" id="verifyCode"
						value={this.state.verifyCode} showUnderLine={true} showTagText={true} creditCodeImg={this.state.verifyCodeImg} creditWidth = {this.state.verifyCodeWidth}
						onClick={()=>{
							this.setState({
								verifyCode: '',
								verifyCodeImg: 'hideDelete',
								verifyCodeNoBlur: false
							})
							document.querySelector('#verifyCode').focus();
						}}
						onBlur={(event)=>{
							let res = event.target.value;
							this.setState({verifyCodeNoBlur: true});
							setTimeout(()=>{
								if(!this.state.verifyCodeNoBlur) return;  //点击删除按钮不执行验证
								let value = res,
									verifyCodeRule = /^0?1[3|4|5|7丨8][0-9]\d{8}$/;

								if(value == ''){
									this.setState({
										verifyCodeImg: '',
									});
								}else if(verifyCodeRule.test(value)){
									this.setState({
										verifyCodeImg: 'correct',
										verifyCodeWidth: '.4rem'
									});
								}else {
									this.setState({
										verifyCodeWidth: '.4rem',
										verifyCodeImg: 'error'
									})
								}
							},0)
						}}

						onFocus={(e)=>{
							let value = e.target.value;
							if(value.length!=0&&value==this.state.verifyCode){
								this.setState({
									verifyCodeImg: 'showDelete',
								});
							}
						}}

						onChange={(e) => {
							let value = e.target.value;
							if(value.length>0&&value!=' '){
								this.setState({
									verifyCodeImg: 'showDelete',
									verifyCode: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
								});
							}else {
								this.setState({
									verifyCodeImg: 'hideDelete',
									verifyCode: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
								});
							}
					}}/>
					<span className={style.verifyCode} onClick={()=>{this.verifyCodeTap()}}>{this.state.verifyCodeText}</span>
				</div>
				{/* 上传图片-start- */}
				<div className={style.uploadImg+' border_bottom_1'} onClick={()=>{this.toUrl('uploadPage/idCard')}}>
					<span>手持身份证照片</span>
					<div className={style.idCardExample}>
						<img src={this.props.idCardImg.file.indexOf('http')>-1?this.props.idCardImg.file:'./images/photoTemplate.png'}></img>
					</div>
				</div>

				<div className={style.uploadImg} onClick={()=>{this.toUrl('uploadPage/insurance')}}>
					<span>交强险保单</span>
					<div className={style.idCardExample}>
						<img src={this.props.insuranceImg.file.indexOf('http')>-1?this.props.insuranceImg.file:
						'./images/photoTemplate.png'
						}></img>
					</div>
				</div>
				{/* 上传图片-end- */}
				<div style={{height: '.4rem',background: '#f2f2f2'}}></div>

				<div className={style.bt}>
					<button className={style.submit} onClick={()=>{this.confirmOrder()}}>下一步</button>
				</div>
				{/* <button type='button' className={style.submit}>下一步</button> */}
				
			</div>	
		)
	}
}

//使用context
AddInfo.contextTypes = {
	router: React.PropTypes.object.isRequired
};

AddInfo.defaultProps = {
	insuranceImg: {
		file:''
	},
	idCardImg: {
		file:''
	}

};

function mapStateToProps(state) {
    return Object.assign({}, state.uploadPageResult)       
}


export default connect(mapStateToProps)(AddInfo);
